var zaTool=window.zaTool||{};

(function(zaTool){

   	var loadingTpl;
	var zaAjax=function(options,successCallback,failureCallback){
				var defaultOptions=$.extend({
					 type:"post",
					 dataType:"json",
					 contentType : "application/x-www-form-urlencoded; charset=utf-8",
					 timeout:20000,
					 async:false,
					 beforeSend:function(xhr, settings){
					 	  	 loadingTpl=  zaTool.zaDialog({msg:'正在加载数据...'},"loading");
					 },
					 success:function(data, status, xhr){
					 	 loadingTpl.remove();
					 	if(successCallback)
						 	successCallback(data);
					 },
					 error:function(xhr, errorType, error){
					 	 loadingTpl.remove();
					 	if(failureCallback)
						 	failureCallback(error);
					 },
					 complete:function(xhr, status){
					 		 loadingTpl.remove();
					 }
				},options?options:{});


				$.ajax(defaultOptions);

		};

        zaTool.zaAjax=zaAjax;
})(window.zaTool);


(function(zaTool){

	
/*******************************************************************************
 * 
 * @version 1.0
 * @author cargepeng
 * @createDate 2012.11.15
 * @updaeDate 2012.11.15
 * @example
function showAlert(){
	zaTool.zaDialog.({msg:'alert内容'} , 'alert',function(){
		alert('你点击了确定');
	});
}
function showConfirm(){
	 zaTool.zaDialog.({msg:'alert内容'} , 'confirm',function(){
		alert('你点击了确定');
	});
}

function showFlash(){
	zaTool.zaDialog.({msg:'操作成功',duration: 1000},”flash“);
}
function showLoading(){
	zaTool.zaDialog.({msg:'操作成功'},“loading");
}
***********************************************************************************/


	var Dialog = function(options) {
		var settings = {
			type : Dialog.ALERT,
			msg : '', //提示内容
			title:"温馨提示",
			confirmText : '确定', // "确定"按钮的文本
			cancelText : '取消', // "取消"按钮的文本
			duration : 1000, // 对于SUCCESS和FAILED 浮层 自动消失所用时间，单位毫秒
			hasMask : true,// 控制是否显示遮罩层，默认为显示遮罩层
			onConfirm : function(){},
			onCancel : function(){}
		};
		
		this._settings = $.extend(settings, options);
		
		/*********************************
		 * 以下变量请勿在类外操作
		 ********************************/
		this._$container = null;// 对话框的根节点，主要用于定位
		this._$dialog = null;//能看到的对话框实体，可用于调整宽度高度等
		this._$pageBody = $('body');// 页面的body节点，所以调用该函数时，应该在body出现之后调用
		this._$mask = null;// 遮罩层
		this._hasRemoved = false;// 判断当前对话框节点和遮罩层是否从dom中删除，防止内存泄漏
		this.onConfirm = this._settings.onConfirm;// 点击"确定"按钮触发的事件
		this.onCancel = this._settings.onCancel;// 点击"取消"按钮触发的事件
		
		this.show();

	};

	/********************************************************************************************
	 * 对话框内容类型的几种形态
	 *******************************************************************************************/
	Dialog.ALERT = "alert";
	Dialog.CONFIRM = "confirm";
	Dialog.FLASH = "flash";
	Dialog.LOADING = "loading";

	/********************************************************************************************
	 * 显示对话框最底层接口
	 * 
	 * @params {object} 对话框参数，各个参数的含义，请参阅Dialog()中的参数
	 *******************************************************************************************/
	Dialog.prototype.show = function(params) {
		this.remove();// 删除以前的对话框内容

		this._hasRemoved = false;// 新的对话框节点已经加入dom中
		this.showMask();// 试图显示蒙板，是否真正显示在该函数里面控制
		
		this._$container = $('\
		  <div class="g_pop">\
			<div class="gp_wrap">\
				<div class="gp_title"><h1></h1></div>\
			    <div class="gp_hd"></div>\
			</div>\
		  </div>\
		');
		
		/***************************************
		 * 重置关键属性，防止CSS文件修改导致异常
		 **************************************/
		this._$container.css({top:0, left:0, width:'100%'});
		
		//存入主体内容
		this._$dialog = this._$container.find('.gp_wrap');

		var $popHd = this._$dialog.find('.gp_hd');

		var $popTitle=this._$dialog.find(".gp_title");
		$popHd.html(this._settings['msg']);
		
		var self = this;//用于行程闭包的自引用
		
		/******************************************************
		 * 显示确定和取消的按钮
		 *****************************************************/
		 if(this._settings['title']){
		 	$popTitle.find("h1").html(this._settings['title']);
		 	$popTitle.css("display","block");
		 }

		if(this._settings['type']== Dialog.ALERT 
				|| this._settings['type'] == Dialog.CONFIRM
		){
			var $popFt = $('<div class="gp_ft"></div>');
			if(this._settings['confirmText']){
				var $confirm = $('<span href="javascript:;" class="z_d_ok">' + this._settings['confirmText'] + '</span>');
				if(this._settings['type']==Dialog.CONFIRM){
					$confirm = $('<span href="javascript:;" class="z_d_ok btn-1">' + this._settings['confirmText'] + '</span>');
				}
				$confirm.appendTo($popFt);

			$confirm.on("click", function(){
					if($.isFunction(self.onConfirm)){
						self.onConfirm();
					}
					self.remove();
					return false;
				});
			}
			if(this._settings['cancelText']&&this._settings['type']==Dialog.CONFIRM){
				var $cancel = $('<span href="javascript:;"  class="z_d_cancel btn-2">' + this._settings['cancelText'] + '</span>');
				
				$cancel.appendTo($popFt);
					$cancel.on("click", function(){
					if($.isFunction(self.onCancel)){
						self.onCancel();
					}
					self.remove();
					return false;
				});
			}
			this._$dialog.append($popFt);
		}
		this._$container.appendTo(this._$pageBody);// 把当前对话框插入dom中

		this.setPosition();// 设置对话框的显示位置
		
		$(window).on('resize', function(){
			self.resizeMask();
			self.setPosition();
		});// 移除页面焦点;

		
		/******************************************************
		 * 处理自动消失
		 *****************************************************/
		if(this._settings['type'] == Dialog.FLASH){
			window.setTimeout(function(){
				self.animateRemove();
			}, this._settings['duration']);
		}
		
		return this;
	};
	
	

	/********************************************************************************************
	 * 添加蒙板 <div class="mod_pop_$mask"></div>
	 *******************************************************************************************/
	Dialog.prototype.showMask = function() {
		if (this.noMask) {
			return;
		}
		this._$mask = $('<div class="g_pop_mask"></div>');
        this.resizeMask();
		this._$mask.appendTo(this._$pageBody);
	};

	/********************************************************************************************
	 * 调整蒙板大小
	 *******************************************************************************************/
    Dialog.prototype.resizeMask = function() {
        if (this._hasRemoved) {
            return;
        }
        var doc = document;
        var width = Math.max(doc.documentElement.scrollWidth, doc.body.scrollWidth);
        var height = Math.max(doc.documentElement.scrollHeight, doc.body.scrollHeight);
        var clientHeight = (doc.compatMode=="CSS1Compat") ? doc.documentElement.clientHeight : doc.body.clientHeight;
    
        height = Math.max(height, clientHeight);
        
        this._$mask.css({width : width + 'px', height : height + 'px'});
    };

	/********************************************************************************************
	 * 移除蒙板
	 *******************************************************************************************/
	Dialog.prototype.remove = function() {
		if (this._$mask) {
			this._$mask.remove();
			this._$mask = null;
		}

		if (this._$dialog) {
			this._$dialog.parent(".g_pop").remove();
			this._$dialog = null;
		}

		this._hasRemoved = true;// 当前对话框节点和遮罩层从dom中删除
	};

	/********************************************************************************************
	 * 用渐变方式删除整个对话框
	 *******************************************************************************************/
	Dialog.prototype.animateRemove = function() {
		var self = this;
		this._$dialog.animate(
			{
				opacity: 0
			},
			{
				duration : 500,
				complete : function(){
					self.remove();//删除节点
				}
			}
		);
	};

	/********************************************************************************************
	 * 设置对话框的显示位置
	 *******************************************************************************************/
	Dialog.prototype.setPosition = function() {
		if (this._hasRemoved) {
			return;
		}

		var dialogWidth = this._$dialog.width();
		var dialogHeight = this._$dialog.height();

		var doc = document;
		var domWidth = (doc.compatMode == "CSS1Compat") ? doc.documentElement.clientWidth : doc.body.clientWidth;
		var domHeight = (doc.compatMode == "CSS1Compat") ? doc.documentElement.clientHeight : doc.body.clientHeight;
		var windowHeight=$(window).height();
		domHeight=Math.max(domHeight,windowHeight);
		var style = {};
		style['marginTop'] = parseInt((domHeight - dialogHeight) * 0.5) + 'px';// 0.618为黄金分割点比例值
		//style['left'] = parseInt((domWidth - dialogWidth) / 2) + 'px';
	
		this._$dialog.css(style);
		//解决遮罩半屏问题
		setTimeout(function(){
			var scrollTop=$(window).scrollTop();
			$(window).scrollTop(scrollTop-2);
		},20);
	};




	/********************************************************************************************
	 * 模拟window.alert，如果想在用户点击"确定"后执行一定行为，请扩充Dialog.onConfirm函数
	 * 
	 * @param {string}
	 *            msg 提示的内容，该参数为必选参数
	 * @param {string}
	 *            confirmText 替代"确定"按钮的文字，该参数为可选参数
	 *******************************************************************************************/
	Dialog.alert = function(msg, confirmText) {
		var options = {
			msg : msg || ' ',
			type : Dialog.ALERT,
			confirmText : '确定'
		};

		return new Dialog(options);
	};

	/********************************************************************************************
	 * 模拟window.confirm，如果想在用户点击"确定"或者"取消"后执行一定行为，请分别扩充Dialog.onConfirm和Dialog.onCancel函数
	 * 
	 * @param {string}
	 *            msg 提示的内容，该参数为必选参数
	 * @param {string}
	 *            confirmText 替代"确定"按钮的文字，该参数为可选参数
	 * @param {string}
	 *            cancelText 替代"取消"按钮的文字，该参数为可选参数
	 *******************************************************************************************/
	Dialog.confirm = function(msg, confirmText, cancelText) {
		var options = {
			msg : msg || ' ',
			type : Dialog.CONFIRM,
			confirmText : '确定',
			cancelText : '取消'
		};
		return new Dialog(options);
	};


	/********************************************************************************************
	 * 提示成功，过段时间自行消失
	 *******************************************************************************************/
	Dialog.flash = function(msg, duration) {
		var options = {
			msg : msg || '',
			type : Dialog.FLASH,
			duration : parseInt(duration) > 0 ? parseInt(duration) : this._settings.duration
		};
		return new Dialog(options);
	};

	/********************************************************************************************
	 * 显示loading状态
	 *******************************************************************************************/
	Dialog.loading = function(msg) {
		msg = '<div class="loading-img"></div><p class="gp_text">' + msg + '</p';
		var options = {
			msg : msg,
			title:"",
			type : Dialog.LOADING
		};
		return new Dialog(options);
	};


	var zaDialog=function(options,type,callback){

			options.type=type;
			options.onConfirm=callback;
			if(type=="flash"){
				return new Dialog.flash(options.msg,options.duration);

			}
			if(type=="loading"){
				return new Dialog.loading(options.msg);
			}
			
			return new Dialog(options);
			

	};
		
	zaTool.zaDialog =zaDialog;


})(window.zaTool);



/**购物车**/

(function(zaTool){



		var CountTool=function(id,params){


			this.options=$.extend({
					plusCls:".plus",
					addCls:".add",
					countNumCls:".count-num",
					spanText:".ct_num",
					disabledCls:"bd_disabled",
					srcNode:null,
					currentCount:null,
					maxNum:999,
					minNum:1,
					clickCallback:function(){},
					limitMinEvent:function(){},
					limitMaxEvent:function(){}

			},params);

			if(!id) return;
			var $count=$("#"+id);
			this.options.el=$count;
			var _self=this;
			var $countText=$count.find(_self.options['spanText']);
			$countText.val(_self.options['minNum']);
			$count.find(_self.options['plusCls']).on("click",function(ev){

					var currentCount=parseInt($(_self.options['srcNode']).val());
					if(isNaN(currentCount)){
						 $countText.val(_self.options['minNum']);
						 return;
					}
					if(parseInt($countText.val())<=_self.options['minNum']){
						$countText.val(_self.options['minNum']);
						_self.options['currentCount']=$countText.val();
						$count.find(_self.options['plusCls']).addClass(_self.options['disabledCls']);
							if($.isFunction(_self.options['limitMinEvent'])){
								_self.options['limitMinEvent'].call(this);
								return;
							}

					}
					else{
						$count.find(_self.options['plusCls']).removeClass(_self.options['disabledCls']);
						$countText.val(parseInt($countText.val())-1);
						_self.options['currentCount']=$countText.val();
					}

					if($.isFunction(_self.options['clickCallback'])){
						  _self.options['clickCallback'].call(this);
					}

			});

			$count.find(_self.options['addCls']).on("click",function(ev){

					var currentCount=parseInt($(_self.options['srcNode']).val());
					if(isNaN(currentCount)) {
						$countText.val(_self.options['minNum']);
						return;
					
					}
					$count.find(_self.options['plusCls']).removeClass(_self.options['disabledCls']);
					if(parseInt($countText.val())>=_self.options['maxNum']){
						$countText.val(_self.options['maxNum']);
						_self.options['currentCount']=$countText.val();
						if($.isFunction(_self.options['limitMaxEvent'])){
								_self.options['limitMaxEvent'].call(this);
								return;
						}
					}
					else{
						$countText.val(parseInt($countText.val())+1);
						_self.options['currentCount']=$countText.val();
					}

					if($.isFunction(_self.options['clickCallback'])){
						  _self.options['clickCallback'].call(this);
					}


			});
				if(_self.options['srcNode']!=null){
						$(_self.options['srcNode']).on(" keyup",function(){
							
							var currentCount=$(_self.options['srcNode']).val();
							if(!Life.Validate(Life.Validate.POSITIVE_INT, currentCount)){
									$countText.val("");
									return;
							}
						
							if(parseInt($countText.val())>=_self.options['maxNum']){
								$countText.val(_self.options['maxNum']);
								_self.options['currentCount']=$countText.val();
							}
							if($.isFunction(_self.options['clickCallback'])){
								_self.options['clickCallback'].call(this);
							}
						});
					}
		};

		CountTool.prototype.getCount=function(){
			var _self=this;
			var $countText=_self.options.el.find(_self.options['spanText']);
			return parseInt($countText.val());

		}


		CountTool.prototype.setMaxNum=function(maxNum){
			var _self=this;
			 _self.options['maxNum']=maxNum;
			var $countText=this.options.el.find(_self.options['spanText']);
			 if(parseInt($countText.val())>maxNum){
			 	$countText.val(maxNum);
			 }
		}

		CountTool.prototype.setMinNum=function(minNum){
			var _self=this;
			 _self.options['minNum']=minNum;
			 var $countText=this.options.el.find(_self.options['spanText']);
			  if(parseInt($countText.val())<minNum){
			 	$countText.val(minNum);
			 }

		}

		CountTool.prototype.getMaxNum=function(){
			var _self=this;
			 
			return _self.options['maxNum'];
		}
		CountTool.prototype.getMinNum=function(){
			var _self=this;
			return _self.options['minNum'];
		}

		var zaCount=function(id,params){

				return new CountTool(id,params);

		}

       zaTool.zaCount=zaCount;


})(window.zaTool);

/**购物计划**/

(function(zaTool){

   var zaGroupCheck=function(id,params){

   		   this.options=$.extend({
   		   	    btnCheckCls:".btn-check",
   		   	    checkActiveCls:".checked",
   		   	    checked:"checked",
   		   	    checkMin:1,
   		   	    defaultCheckIndex:0,
   		   	    clickCallback:function(){},
   		   	    type:"radio",//radio,check
   		   	    limitCheckMax:function(){},
   		   	    checkMax:100
   		   },params);
   		   if(!id) return;

   		   this.options.el=$("#"+id);
   		   var _self=this;
   		   var $checkList=_self.options['el'].find(_self.options['btnCheckCls']);
			if($checkList.length){
   				_self.clearCheck();
   				$($checkList[_self.options['defaultCheckIndex']]).addClass(_self.options['checked']);
   			}

   		   if($checkList.length){
   		   	    $checkList.each(function(index,dom){
   		   	    	$(dom).on("click",function(){
   		   	    			if(_self.options['type']=="radio"){
   		   	    				_self.clearCheck();
   		   	    			}

   		   	    			$(this).toggleClass(_self.options['checked']);


   		   	    			if(_self.getCheckedNum()>_self.options['checkMax']){
   		   	    				     $(this).removeClass(_self.options['checked']);
	   		   	    				if($.isFunction(_self.options['limitMaxEvent'])){
										_self.options['limitCheckMax'].call(this);
										
									}
   		   	    				
   		   	    			}

   		   	    			if(_self.getCheckedNum()<_self.options['checkMin']){
   		   	    				     $(this).removeClass(_self.options['checked']);
	   		   	    				if($.isFunction(_self.options['limitMinEvent'])){
										_self.options['limitCheckMin'].call(this);
										
									}
   		   	    				
   		   	    			}
   		   	    			if($.isFunction(_self.options['clickCallback'])){
								  _self.options['clickCallback'].call(this);
							}
   		   	    			

   		   	    	});
   		   	    });
   		   }







   }

   zaGroupCheck.prototype.getChecked=function(){
   				var _self=this;
   				var checkList=_self.options['el'].find(_self.options['checkActiveCls']);
   				return checkList;


   }

   zaGroupCheck.prototype.setCheckMin=function(minNum){
   			var _self=this;
   			_self.options['checkMin']=minNum;

   }

   zaGroupCheck.prototype.getCheckedNum=function(){
   			var _self=this;
   			var checkList=_self.options['el'].find(_self.options['checkActiveCls']);
   			return checkList.length;

   }
   zaGroupCheck.prototype.setCheckMax=function(maxNum){
   			var _self=this;
   			_self.options['checkMax']=maxNum;

   }

   zaGroupCheck.prototype.clearCheck=function(){
   			var _self=this;
   			var checkList=_self.options['el'].find(_self.options['btnCheckCls']);
   			if(checkList.length){
   				checkList.each(function(index,dom){
   					$(dom).removeClass(_self.options['checked']);
   				})

   			}

   }

   zaGroupCheck.prototype.setcheckedByIndex=function(index){
   			var _self=this;
   			var checkList=_self.options['el'].find(_self.options['btnCheckCls']);
   			if(checkList.length){
   				_self.clearCheck();
   				$(checkList[index]).addClass(_self.options['checked']);
   			}
   }


   var zaCheck=function(id,params){

				return new zaGroupCheck(id,params);

	}


   zaTool.zaCheck=zaGroupCheck;


})(window.zaTool);


(function(zaTool){
	
	var phoneSplitFunc=function(el){
			var value=el.val();
			if(value.length==11){
				    var firstStr=value.substring(0,3)+" ";
				    var secondStr=value.substring(3,7)+" ";
				    var thirdStr=value.substring(7,11);
				    el.val(firstStr+secondStr+thirdStr);
				    el.addClass("text-bold");
			}
	}
	
	zaTool.phoneSplitFunc=phoneSplitFunc;
})(window.zaTool);

/********************************************************************************************
 * 众安联盟微信支付（调用微信支付接口前调用weixinPayAjax.do）
 * 
 * @param {options}
 *            
 * @param {successCallback}
 *            调用成功后的回调方法
 * @param {failureCallback}
 *            调用weixinPayAjax.do失败后的回调方法
 *******************************************************************************************/
(function(zaTool) {

	var weixinPayAjax = function(options, successCallback, failureCallback) {
		var  loadingTpl=  zaTool.zaDialog({msg:'正在加载数据...'},"loading");
		var defaultOptions = $.extend({
			type : "post",
			dataType : "json",
			contentType : "application/x-www-form-urlencoded; charset=utf-8",
			timeout : 20000,
			/*async : false,*/
			success : function(data, status, xhr) {
				loadingTpl.remove();
				var result = eval(data);
				if (result.isSuccess == 'Y') {
					//调用微信支付接口
					Life.WeiXin.callPay({
						"appId" : result.appId,
						"timeStamp" : result.timeStamp,
						"nonceStr" : result.nonceStr,
						"package" : result.package,
						"signType" : result.signType,
						"paySign" : result.paySign
					}, successCallback, payFailed, payCancel);
					
				} else {
				
					alert(result.errMsg);
				}
			},
			error : function(xhr, errorType, error) {
				loadingTpl.remove();
				alert("连接微信支付失败！");
			}
		}, options ? options : {});

		$.ajax(defaultOptions);

	};

	zaTool.weixinPayAjax = weixinPayAjax;
	
	var payFailed = function() {
		alert('微信支付失败！');
		return;
	}
	zaTool.payFailed = payFailed;
	
	var payCancel = function() {
		return;
	}
	zaTool.payCancel = payCancel;
	
})(window.zaTool);